package com.definity.toolkit.web.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class BaseContextFilter implements Filter {

	private Locale defaultLocale;
	private List<String> locales;

	public void init(FilterConfig cfg) throws ServletException {
		String locales = cfg.getInitParameter("locales");
		this.locales = Arrays.asList(locales.split(","));
		
		String param = cfg.getInitParameter("default");
		if (param != null) {
			defaultLocale = new Locale(param.substring(0, 2), param.substring(3));
		}
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		
		String port = "";
		if (request.getServerPort() != 80) {
			port = ":" + request.getServerPort();
		}
		String domain = httpRequest.getScheme() + "://" + request.getServerName() + port;
		request.setAttribute("domain", domain);
		
		String contextPath = httpRequest.getContextPath();
		request.setAttribute("base", contextPath);
		
		Locale locale = (Locale) httpRequest.getSession().getAttribute("defaultLocale");
		if (locale == null) {
			locale = request.getLocale();
			
			if (!locales.contains(locale.toString()))
				locale = defaultLocale;
			
			httpRequest.getSession().setAttribute("defaultLocale", locale);
		}
		
		Locale.setDefault(locale);
		
		chain.doFilter(request, response);
	}

	public void destroy() {
		
	}

}
